#include "AOProgressDialog.h"
#include <cfloat>
#include <QVBoxLayout>
#include <climits>
void AOProgressDialog::updateProcessedPoints(int meshNum, int numPoints)
{
	if(!haveAnyPointsArrived)
	{
		haveAnyPointsArrived = true;
		firstPointTime = QTime::currentTime();
	}
	statusVector[meshNum].nowPoints = numPoints;
	updateDisplay();
}

void AOProgressDialog::updateDisplay()
{
	unsigned long int totalPoints=0;
	unsigned long int totalNowPoints=0;
	for(unsigned int i=0;i<statusVector.size();i++)
	{
		totalPoints+=statusVector[i].totalNumPoints;
		totalNowPoints+= statusVector[i].nowPoints;
	}

	QString text(tr("Number of processed points: "));
	text+=QString().setNum(totalNowPoints);
	text+=tr(" of ");
	text+=QString().setNum(totalPoints);
	text+=".\n";
	text+=tr("Estimated remaining time: ");
	QTime now = QTime::currentTime();
	long int msecsSoFar = firstPointTime.msecsTo(now);
	long int estimatedmsecs;
	if(totalNowPoints == 0)
		estimatedmsecs = ULONG_MAX;
	else
		estimatedmsecs= msecsSoFar / totalNowPoints * (totalPoints-totalNowPoints);

	unsigned long int minutesRemaining = estimatedmsecs/60/1000;
	text+=QString().setNum(minutesRemaining);
	text+=tr(" minutes, ");
	text+=QString().setNum(estimatedmsecs/1000%60);
	text+=tr(" seconds.");
	label->setText(text);
	if(totalNowPoints != 0)
	{
		bar->setRange(0,totalPoints);
		bar->setValue(totalNowPoints);
	}
}

AOProgressDialog::AOProgressDialog(QWidget * parent,std::vector<int>pointsPerMesh): QDialog(parent)
{
	m_mustStopProcessing = false;
	haveAnyPointsArrived = false;
	int globalNumPoints =0;
	for(unsigned int i=0;i < pointsPerMesh.size();++i)
	{
		MeshInfo m;
		m.nowPoints = 0;
		m.totalNumPoints = pointsPerMesh[i];
		globalNumPoints+= pointsPerMesh[i];
		m.estimatedTime = __FLT_MAX__;
		m.finished = false;
		statusVector.push_back(m);
	}
	label = new QLabel(this);
	bar = new QProgressBar(this);
	bar->setMaximum(globalNumPoints);
	bar->setRange(0,0);
	label->setText("Calculando normales");
	QVBoxLayout *layout = new QVBoxLayout;
	QLabel *label2 = new QLabel(this);
	label2->setText("\tPress <ESCAPE> to stop the calculation.");
	layout->addWidget(label);
	layout->addWidget(bar);
	layout->addWidget(label2);
	setLayout(layout);
}

void AOProgressDialog::meshFinished(int numMesh)
{
	printf("Finalizada malla %i-------\n",numMesh);
	statusVector[numMesh].finished = true;

	// If all meshes are finished, we end the dialog
	for(unsigned int i=0;i<statusVector.size();i++)
		if(!(statusVector[i].finished))
			return;

	done(0);
}

AOProgressDialog::~AOProgressDialog()
{
	label->deleteLater();
}

void AOProgressDialog::done(int i)
{
	m_mustStopProcessing = true;
	emit stopAOProcessing();
	printf("EMMITED STOP SIGNAL!!!!!!!!!!!!\n");
	QDialog::done(i);
}
